import React from 'react';
import { Form, Input, Button, message, Card, Typography } from 'antd';
import { LockOutlined, MobileOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { registerUser } from '../redux/features/userSlice';
import { validatePhone } from '../utils/tools';
import './RegisterPage.css';

const { Title, Paragraph } = Typography;

const RegisterPage = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const { isLoading, error, isAuthenticated } = useSelector((state) => state.user);

  // 处理注册
  const handleRegister = async (values) => {
    try {
      await dispatch(registerUser(values)).unwrap();
      message.success('注册成功，正在跳转到登录页');
      // 注册成功后跳转到登录页
      setTimeout(() => {
        window.location.href = '/login';
      }, 1500);
    } catch (error) {
      message.error(error?.message || '注册失败，请稍后再试');
    }
  };

  // 清除错误信息
  React.useEffect(() => {
    if (error) {
      const timer = setTimeout(() => {
        // 这里应该调用clearError，但暂时先注释
        // dispatch(clearError());
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [error, dispatch]);

  // 如果已经登录，直接跳转到首页
  React.useEffect(() => {
    if (isAuthenticated) {
      window.location.href = '/';
    }
  }, [isAuthenticated]);

  // 验证手机号码
  const validatePhoneNumber = (rule, value) => {
    if (!value) {
      return Promise.reject('请输入手机号码');
    }
    if (!validatePhone(value)) {
      return Promise.reject('请输入有效的手机号码');
    }
    return Promise.resolve();
  };

  return (
    <div className="register-container">
      <Card className="register-card">
        <div className="register-header">
          <Title level={2}>用户注册</Title>
          <Paragraph>欢迎使用设备二维码管理系统</Paragraph>
        </div>
        
        <Form
          form={form}
          layout="vertical"
          onFinish={handleRegister}
          className="register-form"
        >
          <Form.Item
            label="手机号码"
            name="phone"
            rules={[
              { validator: validatePhoneNumber }
            ]}
          >
            <Input
              prefix={<MobileOutlined className="input-prefix" />}
              placeholder="请输入手机号码"
              maxLength={11}
            />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度应在6-20位之间' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="input-prefix" />}
              placeholder="请输入密码"
            />
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次输入的密码不一致');
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="input-prefix" />}
              placeholder="请再次输入密码"
            />
          </Form.Item>

          <Form.Item className="register-button-group">
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={isLoading}
              className="register-button"
            >
              注册
            </Button>
          </Form.Item>
        </Form>
        
        <div className="register-footer">
          <Paragraph>
            已有账号？ <a href="/login">立即登录</a>
          </Paragraph>
        </div>
      </Card>
    </div>
  );
};

export default RegisterPage;